package com.rm.zeyou.util.back;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

public class GetColor {
    private static String hex;

    public static String getSexColor(String url) {
        try {
            // 获取图像的主色调
            Color dominantColor = getDominantColor(ImageIO.read(new URL(url)));

            // 将主色调转换为16进制值
            hex = "#" + Integer.toHexString(dominantColor.getRGB()).substring(2);

            System.out.println("主色调的16进制值：" + hex);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return hex;
    }

    // public static void main(String[] args) {
    //     try {
    //         // 图片的URL地址
    //         String imageUrl = "https://yangfubing.gitee.io/bank.logo/resource/logo/CCB.png";
    //
    //         // 通过URL读取图片并转换为BufferedImage对象
    //         URL url = new URL(imageUrl);
    //         BufferedImage image = ImageIO.read(url);
    //
    //         // 获取图像的主色调
    //         Color dominantColor = getDominantColor(image);
    //
    //         // 将主色调转换为16进制值
    //         String hex = "#" + Integer.toHexString(dominantColor.getRGB()).substring(2);
    //
    //         System.out.println("主色调的16进制值：" + hex);
    //     } catch (IOException e) {
    //         e.printStackTrace();
    //     }
    // }

    private static Color getDominantColor(BufferedImage image) {
        int width = image.getWidth();
        int height = image.getHeight();
        int[] pixels = new int[width * height];
        image.getRGB(0, 0, width, height, pixels, 0, width);

        int maxCount = 0;
        Color dominantColor = null;

        for (int pixel : pixels) {
            Color color = new Color(pixel);
            int count = 0;

            for (int neighborPixel : pixels) {
                Color neighborColor = new Color(neighborPixel);

                if (color.equals(neighborColor)) {
                    count++;
                }
            }

            if (count > maxCount) {
                maxCount = count;
                dominantColor = color;
            }
        }

        return dominantColor;
    }
}
